<?php

namespace App\Models\Service;

class Crc16
{
    public static function calculate(string $rawString): string
    {
        $rawString = str_replace(' ', '', $rawString);
        $hexString = pack('H*', $rawString);
        $crc = 0xFFFF;
        for ($i = 0; $i < strlen($hexString); $i++) {
            $crc ^= ord($hexString[$i]);
            for ($j = 8; $j != 0; $j--) {
                if (($crc & 0x0001) != 0) {
                    $crc >>= 1;
                    $crc ^= 0xA001;
                } else $crc >>= 1;
            }
        }

        $revertByte = self::revertByte($crc);
        return sprintf('%04X', $revertByte);
    }

    static public function revertByte(string $bytes, int $offset = 8): string
    {
        $lowByte = ($bytes & 0xFF00) >> $offset;
        $highByte = ($bytes & 0x00FF) << $offset;
        return $lowByte | $highByte;
    }
}
